<template>
  <div>
    <el-table
      v-loading="tableLoading"
      row-key="id"
      header-row-class-name="custom-table-header"
      :data="tableData"
    >
      <el-table-column
        label="章节名称"
        prop="title"
      >
        <template #default="{row}">
          <el-input v-if="row.edit" v-model="row.title" placeholder="章名称" />
          <span v-else>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="排序"
        prop="sort"
        width="140"
      >
        <template #default="{row}">
          <el-input-number
            v-if="row.edit"
            v-model="row.sort"
            :min="0"
            :max="1000"
            style="width: 100%;"
          />
          <span v-else>{{ row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="所属章节"
        prop="lev"
        width="80"
      >
        <template #default="scope">
          <el-tag v-if="scope.row.lev===1">大章</el-tag>
          <el-tag v-else type="success">小节</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="免费"
        prop="isFree"
        width="140"
      >
        <template #default="scope">
          <el-select v-if="scope.row.edit && scope.row.lev!==1" v-model="scope.row.isFree" placeholder="请选择">
            <el-option label="免费" :value="0" />
            <el-option label="收费" :value="1" />
          </el-select>
          <span v-else>
            <el-tag v-if="scope.row.isFree===0">免费</el-tag>
            <el-tag v-else-if="scope.row.isFree===1" type="success">收费</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="时长"
        prop="type"
        width="100"
      >
        <template #default="scope">
          <el-tag v-if="scope.row.duration!=0" type="success">{{ durationFormatDate(scope.row.duration*1000) }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="视频源"
        prop="videoSourceId"
        width="80"
      >
        <template #default="scope">
          <el-tag v-if="scope.row.lev!=1&&scope.row.videoSourceId!=null" effect="dark" type="success" style="cursor: pointer;" @click="playVideoByVideoId(scope.row.videoSourceId,scope.row.title)">播放</el-tag>
          <el-tag v-if="scope.row.videoSourceId===null&&scope.row.lev!=1" effect="plain" type="warning">未上传</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        prop="action"
        width="200"
      >
        <template #default="{row}">
          <template v-if="row.edit">
            <span v-if="row.isNew">
              <el-button type="text" @click="saveRow(row)">添加</el-button>
              <el-popconfirm title="是否要删除此行？" @confirm="remove(row)">
                <template #reference>
                  <el-button type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </span>
            <span v-else>
              <el-button v-if="row.lev===1" type="text" @click="saveRow(row)">保存</el-button>
              <el-button v-else type="text" @click="updateVideo(row)">保存</el-button>
              <el-button type="text" @click="cancel(row)">取消</el-button>
            </span>
          </template>
          <span v-else>
            <el-button type="text" @click="toggle(row.id)">编辑</el-button>
            <el-popconfirm title="是否要删除此行？" @confirm="remove(row)">
              <template #reference>
                <el-button type="text">删除</el-button>
              </template>
            </el-popconfirm>
            <el-button v-if="row.lev!=1&&row.videoSourceId!=null" type="text" title="重新上传视频" @click="uploadVideoById(row.id)">重传</el-button>
            <el-button v-if="row.lev===1 && row.id>0" title="批量导入视频" type="primary" size="mini" icon="el-icon-upload" @click="batchUploadVideoById(row.id)" />
          </span>
        </template>
      </el-table-column>

    </el-table>

    <el-button style="width: 100%;margin-top: 16px; border-style: dashed;" @click="newTableData">
      <i class="el-icon-plus" />
      新增章
    </el-button>
    <div class="dialong__button--wrap">
      <el-button @click="close">取消</el-button>
    </div>

    <!--预览视频-->
    <video-preview
      v-if="dialogVideoVisible"
      :visible="dialogVideoVisible"
      :values="video"
      :on-cancel="() => videoPreviewCancel()"
    />

    <!--上传课程单个小节视频-->
    <upload-video-form
      v-if="uploadVideoFormVisible"
      :visible="uploadVideoFormVisible"
      :values="videoData"
      :header-token="headerToken"
      :on-cancel="() => uploadVideoFormCancel()"
      :get-percent="() => getUploadPercent()"
    />

    <!--批量上传课程小节视频-->
    <batch-upload-video-form
      v-if="batchUploadVideoFormVisible"
      :visible="batchUploadVideoFormVisible"
      :values="chapterData"
      :header-token="headerToken"
      :on-cancel="() => batchUploadVideoFormCancel()"
      :get-percent="getBatchUploadPercent"
    />

  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, PropType, ref, unref, watch, onMounted } from 'vue'
import { InfoWriteParams } from './types'
import VideoPreview from './VideoPreview.vue'
import BatchUploadVideoForm from './BatchUploadVideoForm.vue'
import UploadVideoForm from './UploadVideoForm.vue'
import { delsApi, getChapterTreeListApi, getPlayAuthDataApi, getChapterApi, getBatchUploadPercentApi, setEduChapterApi, updateVideoApi, delsEduChapterApi, delsEduVideoApi, getVideoApi, getUploadPercentApi } from '../api'
import { Message } from '_c/Message'
import { formatDate } from '@/utils/filters'
import wsCache from '@/cache'
import { appStore } from '@/store/modules/app'
export default defineComponent({
  name: 'Detail',
  props: {
    info: {
      type: Object as PropType<any>,
      default: () => null
    }
  },
  emits: ['close', 'saveNewData'],
  components: {
    VideoPreview,
    BatchUploadVideoForm,
    UploadVideoForm
  },
  setup: function(props, { emit }) {
    const form = reactive<InfoWriteParams>({
      id: '', // id
      subjectId: 0, // 课程所示栏目
      title: '', // 长标题
      shortTitle: '', // 短标题
      price: 0, // 价格
      lessonNum: 0, // 课时
      courseDesc: '', // 课程描述
      courseType: 0, // 课程类型
      difficulty: 0, // 课程难度
      remarks: '' // 课程详情
    })

    const subLoading = ref<boolean>(false)
    const tableData = ref<any[]>([])
    const tableLoading = ref<boolean>(false)
    const chapterData = ref<object>()
    const videoData = ref<object>()
    // 上传视频获取token数据
    const headerToken = ref<string|null>()
    const getHeaderToken = () => {
      const token = wsCache.get(appStore.userToken)
      headerToken.value = 'Bearer ' + token
    }
    // 批量上传小节视频
    const batchUploadVideoFormVisible = ref<boolean>(false)
    // 单个上传视频
    const uploadVideoFormVisible = ref<boolean>(false)
    async function getChapterTreeList() {
      if (props.info) {
        const id = (props.info as any).id
        try {
          const res = await getChapterTreeListApi({
            params: {
              courseId: id,
              pageSize: 100
            }
          })

          if (res.code === 0) {
            if (res.data.rows != null) {
              tableData.value = res.data.rows
              console.log('tableData.value', tableData.value)
            }
          }
        } catch (e) {
          console.log(e)
        }
      }
    }
    getChapterTreeList()

    // 新增内容
    const newIndex = ref<number>(0)
    const newTableData = () => {
      const newData = tableData.value.map(item => ({ ...item }))
      newData.push({
        id: newIndex.value,
        title: '',
        sort: '',
        lev: 1,
        duration: 0,
        edit: true,
        isNew: true,
        courseId: (props.info as any).id
      })

      newIndex.value--
      tableData.value = newData
    }

    // 添加、保存
    const saveRow = (record: { id: any; title: any; sort: any;}) => {
      tableLoading.value = true
      const { id, title, sort } = record
      if (!title) {
        tableLoading.value = false
        Message.error('请填写完整环境信息。')
        return
      }
      const target: any = tableData.value.find(item => item.id === id)
      if (target) {
        target.edit = false
        target.isNew = false
        target._originalData = undefined
      }
      tableLoading.value = false
      const newData = tableData.value.map(item => ({ ...item }))
      console.info('添加或保存', newData)
      setEduChapter(id, title, sort)
    }

    // 新增或者编辑课程大章
    async function setEduChapter(id: number, title:string, sort: number) {
      try {
        const res = await setEduChapterApi({
          params: {
            id: id,
            title: title,
            sort: sort,
            courseId: (props.info as any).id
          }
        })
        if (res) {
          Message.success(id ? '编辑成功' : '新增成功')
          await getChapterTreeList()
        }
      } catch (err) {
        console.log(err)
      } finally {
        subLoading.value = false
      }
    }

    // 编辑课程小节
    async function updateVideo(val:any) {
      try {
        const res = await updateVideoApi({
          data: val,
          params: {
            id: val.id
          }
        })
        if (res) {
          Message.success('保存成功')
          await getChapterTreeList()
        }
      } catch (err) {
        console.log(err)
      } finally {
        subLoading.value = false
      }
    }

    function close() {
      emit('close')
    }

    // 删除
    const remove = async(val: any) => {
      if (val.lev > 0) { // 删除课程大章的数据
        const res = await delsEduChapterApi({
          data: JSON.stringify(val.id)
        })
        Message.success(res.message)
      } else { // 删除课程小节的数据
        const res = await delsEduVideoApi({
          data: JSON.stringify(val.id)
        })
        Message.success(res.message)
      }
      await getChapterTreeList()
    }

    // 取消编辑
    const cancel = (key: any) => {
      key._originalData = { ...key }
      key.edit = !key.edit
    }

    // 编辑显示
    const toggle = (key: number) => {
      const target: any = tableData.value.find(item => {
        return item.id === key
      })
      if (target === undefined) { // 编辑课时（小节）
        const childrenTarget: any = tableData.value.find(item => {
          const children:object[] = item.children
          if (children.length > 0) {
            const keyTarget: any = item.children.find((item: { id: number }) => {
              return item.id === key
            })
            if (keyTarget !== undefined) {
              keyTarget._originalData = { ...keyTarget }
              keyTarget.edit = !keyTarget.edit
            }
          } else {
            return null
          }
        })
      } else { // 表示编辑大章
        target._originalData = { ...target }
        target.edit = !target.edit
      }
    }

    // 格式化时长
    const durationFormatDate = (time: any) => {
      const data = new Date(time)
      return formatDate(data, 'hh:mm:ss')
    }

    // 预览视频
    const dialogVideoVisible = ref<boolean>(false)
    // 视频对象
    const video = reactive({
      videoSourceId: '',
      isFree: 0,
      sort: 1,
      fileKey: '',
      titleVideo: '添加课时',
      playAuth: ''
    })
    const playVideoByVideoId = async(videId: string, titleVideo: string) => {
      video.videoSourceId = videId
      video.titleVideo = titleVideo
      const res = await getPlayAuthDataApi({
        params: {
          videId: videId
        }
      })
      console.log('res---:', res)
      if (res.code === 0) {
        video.playAuth = res.data.playAuth
        dialogVideoVisible.value = true
      } else {
        Message.success('播放失败，视频不存在')
      }
    }

    // 取消预览模仿
    const videoPreviewCancel = () => {
      dialogVideoVisible.value = false
      video.videoSourceId = ''
    }

    // 批量上传视频弹框
    const batchUploadVideoById = async(id: number) => {
      const res = await getChapterApi({
        params: {
          id: id
        }
      })
      if (res.code === 0) {
        chapterData.value = res.data
        batchUploadVideoFormVisible.value = true
      }
    }

    // 取消批量上传课程小节视频 弹框
    const batchUploadVideoFormCancel = () => {
      batchUploadVideoFormVisible.value = false
      getChapterTreeList()
    }

    // 批量获取上传进度条
    const getBatchUploadPercent = async(values: any) => {
      console.info('批量上传返回的参数值:', values)
      const response = getBatchUploadPercentApi({
        params: {
          fileKey: values
        }})
      // console.info("index组件获取进度条response:",response.data.percent)
      return response.data.percent
    }

    // 上传视频弹框
    const uploadVideoById = async(id: number) => {
      const res = await getVideoApi({
        params: {
          id: id
        }
      })
      if (res.code === 0) {
        videoData.value = res.data
        setUploadVideoFormVisible(true)
      }
    }
    const setUploadVideoFormVisible = (val: boolean) => {
      uploadVideoFormVisible.value = val
    }

    // 取消上传课程小节视频 弹框
    const uploadVideoFormCancel = () => {
      setUploadVideoFormVisible(false)
      getChapterTreeList()
    }

    // 获取上传进度条
    const getUploadPercent = async() => {
      const response = await getUploadPercentApi({
        params: {
          id: (videoData.value as any).id
        }
      })
      console.info('编辑小节返回值response:', response)
      if (response.code === 0) {
        return response.data.percent
      } else {
        return 0
      }
    }

    watch(tableData.value, () => {
      const newData = tableData.value.map(item => ({ ...item }))
      tableData.value = newData
      console.log('tableData.value,watch:', tableData.value)
    })

    onMounted(() => {
      getHeaderToken()
    })
    return {
      playVideoByVideoId,
      videoPreviewCancel,
      batchUploadVideoById,
      batchUploadVideoFormCancel,
      getBatchUploadPercent,
      updateVideo,
      uploadVideoById,
      uploadVideoFormCancel,
      getUploadPercent,
      dialogVideoVisible,
      batchUploadVideoFormVisible,
      uploadVideoFormVisible,
      form,
      chapterData,
      videoData,
      headerToken,
      close,
      subLoading,
      newTableData,
      tableData,
      tableLoading,
      saveRow,
      setEduChapter,
      toggle,
      cancel,
      remove,
      durationFormatDate,
      video
    }
  }
})
</script>

<style>
</style>
